Do you want your ad here?

Contact us to get your ad seen by thousands of users every day!

[email protected]

42 Practical Java Design Patterns: Builder and More

  • February 27, 2023
  • 7687 Unique Views
  • 4 min read
Table of Contents
Figure 1: Hone your software design skills
Figure 1.: Hone your software design skills

The aim of the article is to introduce my newly published book "Practical Design Pattern for Java Developers".

Together, we'll explore today's application development challenges and dive deeper into some of Java's new language enhancements by exploring  the Builder Design pattern in more detail. 

The days when applications were developed "ad hoc" seem to have ended only on paper.

When it comes to business, "ad hoc" solutions can still be quite common  and accepted, because the "it just works" argument can be strong enough.

Yes, "it works for now" is a winning argument.

Many times such a statement is in direct conflict with the business's understanding, as the unspoken expectation under the hood may be extensibility and maintainability.

So that's the other side of the same coin.

The fact that an application can behave unpredictably after a small extension is not caused by magic, and such a condition could have a negative impact on the use of other practices such as SRE (Site Reliability Engineering, Ref. 4).

Many times the "devil" is hidden in the details of the application's composition and design.

The Java platform may seem quite resistant to such "evils''.

Such thoughts are partly true, because the JVM tries to optimize the code it executes based on its internal statistics, but this is not necessarily successful.

After many years of cross-industry experience, I got the opportunity to get my insights  together in the newly published book "Practical Design Pattern for Java Developers".

The book is not only a collection of 42 design patterns that are being put into today's context, but it also includes many examples linked to the use of the patterns  in the OpenJDK source code.

Figure 2.: Imaginary happiness is enhanced by using design patterns for building software
Figure 2.: Imaginary happiness is enhanced by using design patterns for building software

Although the beautiful pronic number 42 (Figure 2., Ref.6) may seem magical, the selected 42 patterns should provide a final solution to help application designers create a maintainable and extensible code base, along with a strong reflection on new Java enhancements.

My "secret wish" is that the book will help the community to easily adopt all the improvements that have been added to the JDK, not only to noticeably reduce the language verbosity, but also to increase productivity, maintainability, and code security.

Let’s for instance explore together one of the most useful creational design patterns, the Builder (Example 1.), and apply it in the light of record class type (Ref.5.).

Let's say that we would like to create an immutable class "SuperVehicle" with multiple fields.

Fields can be very complex and not all values are known at the same time. The resulting product should be immutable with assessors and comparable to similar types.

It means implementing hashCode and equals. The newly added record class provides us such functionality:

record SuperVehicle(Part engine, Part cabin) implements Vehicle {
    static final class Builder {
        private Part engine;
        private Part cabin;
        Builder(){}
        Builder addEngine(String type) {…}
        Builder addCabin(String type) {…}
        Vehicle build(){
            return new SuperVehicle(this);
        }
    }

    private SuperVehicle(Builder builder) {
        this(builder.engine, builder.cabin);
    }

    @Override
    public void move() {…}

    @Override
    public void parts() {…}
}
System.out.println output:
SuperVehicle[engine=RecordPart[name=super_engine], cabin=RecordPart[name=super_cabin]]

Example 1.: Implementation of the builder pattern using a record class type You may spot the private constructor that denies the instantiation from "outside" and that the class contains a static final Builder class.

The builder provides the fields that are required to create a new SuperVehicle instance. The presented builder pattern uses a newly added record class type. It is straightforward, transparent, and less error-prone than using multiple constructors, sometimes called the telescopic pattern.

The SuperVehicle record class automatically includes assessors, hashCode, equals, and toString methods. As the cherry on the top, the class is immutable by definition. Isn’t that wonderful?

Conclusion

The newly updated builder pattern can contribute to the sustainability of the application code base as well as the stability of the application at runtime.

We have explored a possible implementation of the builder pattern using one of the new Java enhancements.

The book contains many other examples with different implementation proposals.

The text also shows the concurrent nature of the Java platform itself, provides required description of the platform inside and discusses several concurrent design patterns commonly present in today’s application design.

Together in this book, we will reveal not only patterns, but also the many anti-patterns that can be considered a natural byproduct of application development.

The book describes how to identify and respond to them.

Everything is packed into a compact design and supported by closely discussed examples published in a GitHub repository (Ref. 1).

Enjoy reading and happy coding!

References

  1. GitHub Repository: Practical Design Pattern for Java Developers 
  2. Packt: Interview with Miroslav Wengner 
  3. Launch Countdown 101: How I Become a Book Author
  4. Site Reliability Engineering (SRE)
  5. JEP 395: Records 
  6. Wiki: Pronic number
  7. Practical Design Pattern for Java Developers
Book Review: “Effortless Cloud-Native App Development Using Skaffold”

There is no better time than the present for a book such as this, which can surely be seen to be some kind of Skaffold Bible.

The author provides a complete and thorough overview of the central issues faced by users of Kubernetes, presents Skaffold as a solution, highlights its features and pitfalls, while placing it within the context of the broader ecosystem of comparable solutions.

Book Review: “Help Your Boss Help You”

Some books were written to be read once and put aside, others to be read thoroughly several times and then to be placed behind glass to be broken in case of emergency.

This book is of the latter kind—once you’ve read through it a few times, and dipped into the areas that speak to you most, you want to have it nearby both as a PDF and in hard copy format—as a backup just in case you can’t find that PDF at the crucial moment when you really need to have a response at hand in times of crisis.

Book Review: “Java by Comparison”

The book “Java by Comparison” by Simon Harrer, Jörg Lenhard, and Linus Dietz, promises the reader to become a “Java Craftsman” through the study of 70 examples.

The book is published by The Pragmatic Bookshelf.

Each “example” is structured as a before-and-after comparison.

Book Review: “Quarkus for Spring Developers”

Quarkus for Spring Developers is a straight-forward guide to enable senior developers to quickly shift their Spring skills to leverage the “supersonic subatomic” Quarkus framework, and junior/mid-level developers to learn two frameworks at once.

The book gets straight to the point of Quarkus’ speed before the first chapter, with the foreword providing a real world testimonial of Quarkus software that many Java developers already use.

Book Review: “Seriously Good Software”

Marco Faella’s book “Seriously Good Software” teaches intermediate Java programmers to write better software, using an entirely different approach.

I can warmly recommend this book to Java programmers who have learned to code and strive to code well.

I think it is a particularly rewarding read for computer science students who had several semesters of disjointed knowledge of programming, algorithms, computing systems, and software engineering.

Do you want your ad here?

Contact us to get your ad seen by thousands of users every day!

[email protected]

Comments (0)

Highlight your code snippets using [code lang="language name"] shortcode. Just insert your code between opening and closing tag: [code lang="java"] code [/code]. Or specify another language.

No comments yet. Be the first.

Subscribe to foojay updates:

https://foojay.io/feed/
Copied to the clipboard